<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-06-06 14:54:52
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-09-16 17:58:47
 * @FilePath     : \rpms\src\components\selectForTable\index.vue
-->
<template>
  <div :class="className">
    <slot v-if="isCustom" :data="participantList" name="tableData"></slot>
    <el-select
      v-model="userIds"
      clearable
      filterable
      multiple
      placeholder="请输入姓名搜索"
      @change="handlePublicUser"
      :disabled="disabled"
      :remote-method="getUserData"
      style="width: 100%"
      remote
    >
      <el-option
        v-for="item in userList"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      ></el-option>
    </el-select>
    <el-table
      v-if="!isCustom && participantList.length > 0"
      :data="participantList"
      border
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <template #empty>
        <el-empty :image-size="40" description="暂无数据"></el-empty>
      </template>
      <el-table-column type="index" label="序号" />
      <el-table-column prop="name" label="姓名">
        <template #default="scope">
          {{ scope.row?.name.split("-")[0] }}
        </template>
      </el-table-column>

      <el-table-column prop="" label="单位">
        <template #default="scope">
          {{
            scope.row?.companyName ||
            scope.row?.deptName ||
            scope.row?.department
          }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="position" label="职位"></el-table-column>
      <el-table-column prop="positionalTitles" label="职称"></el-table-column> -->

      <!-- <el-table-column prop="kcRoleName" label="角色"></el-table-column> -->
      <el-table-column prop="isEmp" label="是否内部用户">
        <template #default="scope">
          {{ scope.row.isEmp === "0" ? "否" : "是" }}
        </template>
      </el-table-column>
      <el-table-column v-if="rankLable" :label="rankLable">
        <template #default="scope">
          <el-select
            style="width: 100%"
            value-key="key"
            v-model="scope.row.rank"
          >
            <el-option
              v-for="item in authorRanks"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, watch } from "vue";
import { getExpertStaffList } from "/@/api/expert";
import { getUsersForScience } from "/@/api/user";

export default defineComponent({
  name: "selectForTable",
  props: {
    value: {
      type: Array,
      default: () => []
    },
    rankLable: {
      type: String,
      default: null
    },
    className: {
      type: String,
      default: "select-table"
    },
    disabled: { type: Boolean, default: false },
    isUser: { type: Boolean, default: true },
    isCustom: { type: Boolean, default: false },
    selectData: { type: Array, default: () => [] }
  },

  emits: ["change", "load"],
  setup(props, ctx) {
    let userList = ref([]);
    let userIds = ref([]);
    let participantList = ref([]);
    let participants = ref([]);
    let authorRanks = ref([
      { key: "1", label: "一" },
      { key: "2", label: "二" },
      { key: "3", label: "三" },
      { key: "4", label: "其它" }
    ]);
    async function getUserData(query = "") {
      try {
        const params = {
          pageNum: 1,
          pageSize: 0,
          nameLike: query,
          querySource: 1
          // name: query
        };

        const res = props.isUser
          ? await getUsersForScience(params)
          : await getExpertStaffList({
              pageNum: 1,
              pageSize: 200,
              nameLike: query
            });

        if (res.code === 200) {
          participants.value = participants.value.concat(res.data.list);
          // participants.value.map(el => {

          //   if (el.id) {
          //     el["userId"] = el.id;
          //   } else {
          //     el["id"] = el.userId;
          //   }
          // });

          let arr: Array<any> = res.data.list
            .map(item => {
              const deptName = item.deptName || item.companyName;
              return {
                id: item.id,
                name: item.name + (deptName ? "-" + deptName : "-无")
              };
            })
            .concat(userList.value);

          const arr2 = arr.filter((element, index, self) => {
            return self.findIndex(x => x.id === element.id) === index;
          });
          userList.value = [];
          userList.value = arr2;
        }
      } catch (err) {
        console.log(err);
      }
    }

    const handlePublicUser = item => {
      participantList.value = [];
      item.forEach(element => {
        const target = participants.value.find(el => el.id === element);
        if (target) {
          if (target.rank == null) {
            target["rank"] = "1";
          }
          participantList.value.push(target);
        }
      });

      ctx.emit("change", item);
    };
    onMounted(async () => {
      if (props.value.length !== 0) {
        props.value.map((el: any) => {
          userIds.value.push(el.id);
          userList.value.push({ id: el.id, userId: el.userId, name: el.name });
          participants.value.push(el);
        });
        handlePublicUser(userIds.value);
      }
    });
    watch(
      () => props.value,
      newvalue => {
        userIds.value = [];
        participants.value = [];
        newvalue.map((el: any) => {
          userIds.value.push(el.id);
          userList.value.push({ id: el.id, userId: el.userId, name: el.name });
          participants.value.push(el);
        });
        handlePublicUser(userIds.value);
      },

      { immediate: false }
    );
    return {
      getUserData,
      participants,
      userIds,
      userList,
      participantList,
      handlePublicUser,
      authorRanks
    };
  }
});
</script>
<style lang="scss" scoped></style>
